require 'rubygems'
require 'gruff'
require "report/Report"
require "report/Section"

class LayerAccuracy

  NAME = "Accuracy (Layer)"
  def analyze(directory, experimentalData, phraseCards)

    #create the report
    reportname = NAME
    report = Report.new(directory, reportname )

    #get the data by layer
    data = experimentalData.group_by_layer

    data.each_pair do |layer, entries|
      data_by_uid = {}

      entries.each do |e|
        #initialize if nil
        data_by_uid[e.uid] ||= []
        data_by_uid[e.uid] << e
      end

      #create a graph for each layer
      g = create_graph(layer)

      #do some simple statistics
      stat = ""

      #Generate a section for each tech uid
      data_by_uid.each_pair do |uid, entries|
        entries.sort! { |x,y| x.date <=> y.date }

        accuracies = entries.collect do |e|
          _count_backspace(e).to_f / phraseCards.getPhrase(e.set, e.phrase).length
        end   
        
        avg = accuracies.inject{ |sum, el| sum + el }.to_f / accuracies.length  
        
        g.data "UID:#{uid}", accuracies
        stat = stat + "<b>Subject #{uid}:</b> " +  
               "finished(phrases):#{entries.length} " +
               "average error rate: #{avg}" +
               "<br/>" 
      end

      report.new_section("Layer #{layer}", stat, g)
    end

    #generate report
    report.to_html
  end

  def create_graph (layer)
    g = Gruff::Line.new
    g.dot_radius = 2
    g.line_width = 2
    g.x_axis_label = "Phrases"
    g.y_axis_label = "Error"
    g.title =  "Error Rate (Layer:#{layer})"
    g
  end
  
  def _count_backspace(e)
    #count the number of backspace
    counter = 0
    state = :normal
    e.sequence.each do |seq|
      if ( seq[0].eql?("\b"))
        counter = counter + 1 if state == :normal
        state = :consecutive_bs
      else
        state = :normal
      end
    end
    counter
  end
end